package com.tanhua.dubbo.api;

import cn.hutool.core.util.RandomUtil;
import com.tanhua.model.mongo.Peachblossom;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Random;

/**
 * @author : RYR
 * @description : 桃花的实体类
 * @createTime : 2022/1/2 14:51
 */
@DubboService
public class PeachblossomImpl implements PeachblossomApi{

    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 保存语音数据
     * @param peachblossom
     */
    @Override
    public Boolean saveUrl(Peachblossom peachblossom) {
        try {
            mongoTemplate.save(peachblossom);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 随机接收语音数据
     * @param userId 当前id
     * @return
     */
    @Override
    public Peachblossom findRandomUrl(Long userId,String gender) {
        //  排除自己的id
        Criteria criteria = Criteria.where("userId").nin(userId).and("gender").nin(gender);
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.sample(1)  //  随机生成一条
        );
        AggregationResults<Peachblossom> aggregate = mongoTemplate.aggregate(aggregation, Peachblossom.class,Peachblossom.class);
        return  aggregate.getUniqueMappedResult();

    }

    /**
     * 听完之后进行删除
     * @param peachblossom
     */
    @Override
    public void delete(Peachblossom peachblossom) {
        mongoTemplate.remove(peachblossom);
    }
}
